<template>
    <el-table
        ref="tableRef"
        :data="tableData"
        v-bind="tableDefaultAttribute"
        row-key="id"
        :max-height="tableHeight"
        table-layout="auto"
        @cell-dblclick="update"
        @sort-change="handleSortChange"
    >
        <template #empty>
            <span>无数据</span>
        </template>
        <el-table-column type="selection" width="55" :align="'center'" />
        <template v-for="col in tableColumns" :key="col.prop">
            <el-table-column
                v-if="!col.isHidden"
                :align="col.align"
                :prop="col.prop"
                :label="col.label"
                :fixed="col.fixed"
                :formatter="col.formatter"
                :type="col.type"
                :width="col.width"
            >
            </el-table-column>
        </template>
    </el-table>
    <el-button-group class="bg">
        <el-button class="btn" type="primary" :icon="Plus" @click="add"
            >增加</el-button
        >
        <el-button class="btn" type="primary" :icon="Delete" @click="onDelete"
            >删除</el-button
        >
        <el-button class="btn" type="primary" :icon="Search" @click="onQuery"
            >查询</el-button
        >
        <el-button class="btn" type="primary" :icon="Search" @click="auditPay"
            >实收付发票核销</el-button
        >
        <el-button
            class="btn"
            type="primary"
            :icon="Search"
            @click="auditFeedet"
            >应收付发票核销</el-button
        >
        
        <el-button class="btn" type="primary" @click="onPDF">生成PDF</el-button>
        <el-button
            class="btn"
            type="info"
            :icon="Search"
            @click="auditPayDetails"
            >实收付核销明细</el-button
        >
        <el-button
            class="btn"
            type="info"
            :icon="Search"
            @click="auditFeedetDetails"
            >应收付核销明细</el-button
        >
    </el-button-group>
    <div class="page">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[50, 100, 150, 200]"
            layout="sizes, prev, pager, next"
            :total="totalnum"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
    </div>
    <el-dialog
        v-model="dialogUpdateVisible"
        title="发票维护"
        draggable
        destroy-on-close
        :center="true"
        width="90%"
    >
        <Invoice
            :data="paramData"
            @close="onCloseDialog"
            @create="onAdded"
            @update="onUpdated"
        >
        </Invoice>
    </el-dialog>
    <el-dialog
        v-model="dialogAuditPayVisible"
        title="发票核销实收付"
        draggable
        destroy-on-close
        top="5vh"
        width="90%"
    >
        <AuditInvoicePay
            :invoiceids="paramAudit"
            @close="onCloseDialog"
        ></AuditInvoicePay>
    </el-dialog>
    <el-dialog
        v-model="dialogAuditPayDetailVisible"
        title="发票实收付核销明细"
        draggable
        destroy-on-close
        top="5vh"
        width="90%"
    >
        <AuditInvoicePayDetail
            :invoice-no="paramInvoiceNo"
            @close="onCloseDialog"
        ></AuditInvoicePayDetail>
    </el-dialog>
    <el-dialog
        v-model="dialogAuditFeedetDetailVisible"
        title="发票应收付核销明细"
        draggable
        destroy-on-close
        top="5vh"
        width="90%"
    >
        <AuditInvoiceFeedetDetail
            :invoice-no="paramInvoiceNo"
            @close="onCloseDialog"
        ></AuditInvoiceFeedetDetail>
    </el-dialog>
    <el-dialog
        v-model="dialogAuditFeedetVisible"
        title="发票核销应收付"
        draggable
        destroy-on-close
        top="5vh"
        width="90%"
    >
        <AuditInvoiceFeedet
            :invoiceids="paramAudit"
            @close="onCloseDialog"
        ></AuditInvoiceFeedet>
    </el-dialog>
    <el-dialog
        v-model="dialogQueryVisible"
        title="发票查询"
        draggable
        destroy-on-close
    >
        <QueryForm
            :queryItems="queryItems"
            @yh-closedialog="onCloseDialog"
        ></QueryForm>
    </el-dialog>
</template>
<script setup lang="ts" name="Invoices">
import { ref, reactive, onMounted } from 'vue';
import { storeToRefs } from 'pinia';
import { ElMessage, ElMessageBox, ElTable, FormRules } from 'element-plus';
import { Delete, Plus, Search } from '@element-plus/icons-vue';
import {
    isEmpty,
    forEach,
    forEachRight,
    includes,
    findIndex,
    omit,
} from 'lodash';

import type { InvoiceModel, VInvoiceModel } from '@/common/types/business';
import {
    tableDefaultAttribute,
    useTableInfo,
    tableColumnDefault,
} from '@/hooks/useTable';
import type { FormFieldItem, QueryItem, TableColumn } from '@/common/types/app';
import { Request } from '@/app/request';
import {
    initObjectProperty,
    pickFormFromTable,
    pickQueryFromTable,
    transFormatter,
    formatDate,
} from '@/common/tools';
import { tableMaxHeightAdjust } from '@/common/const';
import { useAppStore } from '@/store/app';
import AuditInvoicePay from './AuditInvoicePay.vue';
import AuditInvoicePayDetail from './AuditInvoicePayDetail.vue';
import AuditInvoiceFeedetDetail from './AuditInvoiceFeedetDetail.vue';
import AuditInvoiceFeedet from './AuditInvoiceFeedet.vue';
import Invoice from './Invoice.vue';
const { currency, SelectOptionYN } = storeToRefs(useAppStore());
const tableRef = ref<InstanceType<typeof ElTable>>();
const tableData = ref<Array<VInvoiceModel>>([]);
const paramData = reactive<InvoiceModel>({});
const paramAudit = ref<number[]>([]);
const paramInvoiceNo = ref('');
const tableHeight = ref(100);
/* const formOptions = reactive<{
    labelWidth?: string;
    labelPosition?: string;
}>({});

const rules = reactive<FormRules>({
    from_corp_nam: [
        { required: true, message: '销售方不能为空', trigger: 'blur' },
    ],
    to_corp_nam: [
        { required: true, message: '购买方不能为空', trigger: 'blur' },
    ],
    currency_cod: [{ required: true, message: '请输入货币', trigger: 'blur' }],
    
    invoice_no: [{ required: true, message: '请输入发票号', trigger: 'blur' }],
    
    invoice_date: [
        { required: true, message: '请输入发票日期', trigger: 'blur' },
    ],
    
    cost_amount: [
        { required: true, message: '请输入非含税价', trigger: 'blur' },
    ],
    tax_rate: [{ required: true, message: '请输入税率', trigger: 'blur' }],
    tax_amount: [{ required: true, message: '请输入税额', trigger: 'blur' }],
    amount: [{ required: true, message: '金额不能为空', trigger: 'blur' }],
}); */
const queryFromCorpSearch = async (queryString: string, cb: any) => {
    const req = new Request('过滤发票户头名称', { type: 'from', queryString });
    const r = await req.post();
    if (r.code > 100) {
        cb(r.obj);
    } else {
        cb([]);
    }
};
const queryToCorpSearch = async (queryString: string, cb: any) => {
    const req = new Request('过滤发票户头名称', { type: 'to', queryString });
    const r = await req.post();
    if (r.code > 100) {
        cb(r.obj);
    } else {
        cb([]);
    }
};
const onFormatter = (_row: any, column: any, cellValue: any) => {
    let data: { value: string | number; label: string }[];
    if (
        [
            'audit_finish_id',
            'audit_id',
            'pay_audit_id',
            'feedet_audit_id',
        ].includes(column['property'])
    ) {
        data = SelectOptionYN.value;
    } else if (column['property'] === 'currency_cod') {
        data = currency.value;
    } else {
        return cellValue;
    }

    return transFormatter(cellValue, data);
};
const tableColumns = reactive<TableColumn[]>([
    {
        ...tableColumnDefault,
        order: 1,
        prop: 'from_corp_nam',
        label: '销售方',
        formFieldItemType: 'suggest',
        optionalValues: queryFromCorpSearch,
        width: 200,
    },
    {
        ...tableColumnDefault,
        order: 1,
        prop: 'to_corp_nam',
        label: '购买方',
        formFieldItemType: 'suggest',
        optionalValues: queryToCorpSearch,
        width: 200,
    },

    {
        ...tableColumnDefault,
        order: 4,
        prop: 'invoice_date',
        label: '发票日期',
        formatter: formatDate,
        formFieldItemType: 'date',
        width: 200,
    },
    {
        ...tableColumnDefault,
        order: 5,
        prop: 'invoice_no',
        label: '发票号',
        width: 100,
    },
    {
        ...tableColumnDefault,
        order: 5,
        prop: 'invoice_cod',
        label: '发票代码',
        width: 100,
    },
    {
        ...tableColumnDefault,
        order: 1,
        prop: 'currency_cod',
        label: '货币',
        formatter: onFormatter,
        formFieldItemType: 'single',
        optionalValues: currency.value,
        width: 80,
    },
    /* {
        ...tableColumnDefault,
        order: 5,
        prop: 'tax_no',
        label: '税号',
        width: 100,
    }, */
    {
        ...tableColumnDefault,
        order: 5,
        prop: 'cost_amount',
        label: '未税价',
        formFieldItemType: 'number',
        width: 100,
    },
    {
        ...tableColumnDefault,
        order: 5,
        prop: 'tax_rate',
        label: '税率%',
        formFieldItemType: 'number',
        width: 100,
    },
    {
        ...tableColumnDefault,
        order: 5,
        prop: 'tax_amount',
        label: '税额',
        formFieldItemType: 'number',
        width: 100,
        // noFormField: true,
    },
    {
        ...tableColumnDefault,
        order: 5,
        prop: 'amount',
        label: '金额',
        formFieldItemType: 'number',
        width: 100,
        // noFormField: true,
    },
    {
        ...tableColumnDefault,
        order: 7,
        prop: 'pay_audit_id',
        label: '实收付核销',
        sortable: 'custom',
        formatter: onFormatter,
        formFieldItemType: 'single',
        optionalValues: SelectOptionYN.value,
        noFormField: true,
        width: 150,
    },
    {
        ...tableColumnDefault,
        order: 7,
        prop: 'feedet_audit_id',
        label: '应收付核销',
        sortable: 'custom',
        formatter: onFormatter,
        formFieldItemType: 'single',
        optionalValues: SelectOptionYN.value,
        noFormField: true,
        width: 150,
    },
    {
        ...tableColumnDefault,
        order: 5,
        prop: 'unaudit_pay_amount',
        label: '未核销实收付金额',
        formFieldItemType: 'number',
        width: 100,
        noFormField: true,
    },
    {
        ...tableColumnDefault,
        order: 5,
        prop: 'unaudit_feedet_amount',
        label: '未核销应收付金额',
        formFieldItemType: 'number',
        width: 100,
        noFormField: true,
    },
    {
        ...tableColumnDefault,
        order: 14,
        prop: 'remark',
        label: '备注',
        sortable: 'custom',
        width: 200,
    },
]);

/* const formItems = reactive<Array<FormFieldItem>>(
    pickFormFromTable(tableColumns),
);

const createActionName = ref('发票增加');
const updateActionName = ref('发票修改');
 */
const dialogQueryVisible = ref(false);
const dialogUpdateVisible = ref(false);
const dialogAuditPayVisible = ref(false);
const dialogAuditPayDetailVisible = ref(false);
const dialogAuditFeedetDetailVisible = ref(false);
const dialogAuditFeedetVisible = ref(false);
let queryWhere = {};

const onRefresh = async () => {
    // console.log('参数', paramData);

    const req = new Request('发票查询', {
        skip: (currentPage.value - 1) * pageSize.value,
        take: pageSize.value,
        order: orders,
        ...queryWhere,
    });
    const r = await req.post();

    totalnum.value = r.ext;
    tableData.value.length = 0;

    if (!isEmpty(r.obj)) {
        tableData.value = r.obj;
    }
};
const {
    currentPage,
    orders,
    pageSize,
    totalnum,
    handleSizeChange,
    handleCurrentChange,
    handleSortChange,
} = useTableInfo(onRefresh);
onMounted(() => {
    // onRefresh();
    tableHeight.value =
        window.innerHeight -
        Math.ceil(tableRef.value?.$el.getBoundingClientRect().bottom) +
        tableMaxHeightAdjust;
    // alert(tableHeight.value);
});
const add = () => {
    initObjectProperty(paramData);
    dialogUpdateVisible.value = true;
};
const update = (row: any) => {
    Object.assign(paramData, row);
    dialogUpdateVisible.value = true;
};
const onAdded = (data: VInvoiceModel) => {
    /* data.tax_amount = data.cost_amount! * data.tax_rate! * 0.01;
    data.amount = data.cost_amount! + data.tax_amount;
    data.unaudit_pay_amount = data.amount;
    data.unaudit_feedet_amount = data.amount; */
    tableData.value.unshift(data);
};
const onUpdated = (data: InvoiceModel) => {
    const i = findIndex(tableData.value, (o) => {
        return o.id === data.id;
    });
    if (i > -1) {
        /* data.tax_amount = data.cost_amount! * data.tax_rate! * 0.01;
        data.amount = data.cost_amount! + data.tax_amount; */

        Object.assign(tableData.value[i], omit(data, ['id']));
    } else {
        ElMessage.error('修改失败');
    }
};
const onCloseDialog = async (arg?: any) => {
    if (dialogUpdateVisible.value) {
        dialogUpdateVisible.value = false;
    }
    if (dialogAuditPayVisible.value) {
        onRefresh();
        dialogAuditPayVisible.value = false;
    }
    if (dialogAuditPayDetailVisible.value) {
        dialogAuditPayDetailVisible.value = false;
    }
    if (dialogQueryVisible.value) {
        // 查询
        currentPage.value = 1;
        queryWhere = arg;
        onRefresh();

        dialogQueryVisible.value = false;
    }
};
const getSelectedIds = (): number[] => {
    const rows: Array<InvoiceModel> = tableRef.value?.getSelectionRows() || [];
    if (rows.length === 0) {
        ElMessage.info({
            message: '请选择要删除数据',
        });
        return [];
    }
    const ids = Array<number>();
    forEach(rows, (v: InvoiceModel) => {
        ids.push(v.id as number);
    });
    return ids;
};
const onDelete = async () => {
    const ids = getSelectedIds();
    if (ids.length === 0) {
        return;
    }

    const msg = '';
    // const delids = ids.join(',');
    const cr = await ElMessageBox.confirm(msg, '确认删除', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            return true;
        })
        .catch(() => {
            return false;
        });
    if (cr) {
        //
        const req = new Request('发票删除', { ids });
        const r = await req.post();
        if (r.code > 100) {
            forEachRight(tableData.value, (v: InvoiceModel, i: number) => {
                if (includes(ids, v.id)) {
                    tableData.value.splice(i, 1);
                }
            });
        }
    }
};
const auditPay = () => {
    const ids = getSelectedIds();
    if (ids.length === 0) {
        return;
    }
    paramAudit.value = ids;
    dialogAuditPayVisible.value = true;
};
const auditPayDetails = () => {
    const rows: Array<InvoiceModel> = tableRef.value?.getSelectionRows() || [];
    if (rows.length !== 1) {
        ElMessage.info({
            message: '请选择一个发票',
        });
        return;
    }
    paramInvoiceNo.value = rows[0].invoice_no as string;
    dialogAuditPayDetailVisible.value = true;
};
const auditFeedetDetails = () => {
    const rows: Array<InvoiceModel> = tableRef.value?.getSelectionRows() || [];
    if (rows.length !== 1) {
        ElMessage.info({
            message: '请选择一个发票',
        });
        return;
    }
    paramInvoiceNo.value = rows[0].invoice_no as string;
    dialogAuditFeedetDetailVisible.value = true;
};
const auditFeedet = () => {
    const ids = getSelectedIds();
    if (ids.length === 0) {
        return;
    }
    paramAudit.value = ids;
    dialogAuditFeedetVisible.value = true;
};
const onPDF = async () => {
    const ids = getSelectedIds();
    if (ids.length !== 1) {
        ElMessage.info({
            message: '请选择一个发票',
        });
        return;
    }
    const req = new Request('生成发票PDF', { invoice_id: ids[0] });
    const r = await req.post();
    if (r.code > 100) {
        window.open(r.obj, '_blank');
    }
};
const onQuery = () => {
    dialogQueryVisible.value = true;
};
const queryItems: Array<QueryItem> = pickQueryFromTable(tableColumns);
</script>
<style lang="scss" scoped>
.bg {
    margin-top: 10px;

    .btn {
        margin-right: 10px;
    }
}

.page {
    float: right;
    margin-top: 10px;
}
</style>
